import {INIT_USER_INFO, INIT_USER_INFO_SAGA, REGAIN_USER, USER_SIGN_SAGA} from "@/store/common/user/type";
import {put, select, takeEvery} from 'redux-saga/effects';
import Http from "@/util/http";
import {Api, errorMsg, load, successMsg} from "@/util/global";
import EventBus from "@/util/EventBus";
import {toBase64} from "@/util/CodeUtils";
import {regainUserInfo} from "@/api/SysUserInfo";

const effects = {
    * login() {
        load(true);
        let user = yield select(state => state.toJS().login);
        if (!user.account || !user.password) {
            errorMsg("账号或者密码不能为空")
            load(false);
            return;
        }

        const data = {
            account: user.account,
            // Base64加密
            password: toBase64(user.password)
        };

        const ajax = yield Http.post(Api.LoginApi, data);

        if (ajax.data && ajax.success) {
            let action = {
                type: INIT_USER_INFO,
                value: ajax.data
            };
            yield put(action);
            yield sessionStorage.setItem("just-game-obj", toBase64(ajax.data));
            yield sessionStorage.setItem('token', ajax.data.token);
            yield load(false);
            EventBus.emit("login", true);
            successMsg(ajax.data.uname + ",欢迎登录！");
        } else {
            load(false);
            // errorMsg(ajax.message);
        }
        load(false);
    },
    * sign() {
        let user = yield select(state => state.toJS().login.SignInfo);
        const ajax = yield Http.post(Api.SignUpApi, user);
        if (ajax.success === true) {
            successMsg("恭喜您！注册成功啦。");
            EventBus.emit('sign', true);
        }
    },
    /**
     * 重新获取用户信息
     */
    * regainUserInfo() {
        const ajax = yield regainUserInfo();
        if (ajax.data && ajax.success) {
            let action = {
                type: INIT_USER_INFO,
                value: ajax.data
            };
            yield put(action);
            yield sessionStorage.setItem('token', ajax.data.token);
        }
    }
}

export default function* User() {
    yield takeEvery(INIT_USER_INFO_SAGA, effects.login);
    yield takeEvery(USER_SIGN_SAGA, effects.sign);
    yield takeEvery(REGAIN_USER, effects.regainUserInfo);
}
